<script setup lang="ts">
import { UploadFileAPI } from '@/apis/common';
import { addParkAPI, editParkAPI, parkIndustryAPI, updateParkAPI } from '@/apis/park';
import router from '@/router';
import type { EmptyObjectParams, parkIndustryRes } from '@/types/park';
import { Loading, SuccessFilled, UploadFilled } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { useRoute} from 'vue-router';
import { onMounted, ref } from 'vue';
const route = useRoute()
const industryRes = ref<parkIndustryRes[]>([])
const editId=ref(0)
const getIndustry = async () => {
  const res = await parkIndustryAPI()
  industryRes.value = res.data
}
getIndustry()
const addForm = ref<EmptyObjectParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: undefined // 营业执照id
})
const upload = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'businessLicense')
  const res = await UploadFileAPI(fd)
  addForm.value.businessLicenseUrl = res.data.url
  addForm.value.businessLicenseId = res.data.id
  refForm.value?.validateField('businessLicenseUrl')
  return res.data.url
}
const fileList = ref<UploadUserFile[]>([])
const uploadRule = (rawFile: UploadRawFile) => {
  if (rawFile.size > 5 * 1024 * 1024) {
    ElMessage.warning('图片大小不能超过5M')
    return false
  } else if (['image/jpeg', 'image/png'].includes(rawFile.type) === false) {
    ElMessage.warning('图片格式不正确')
    return false
  }
  return true
}
const addFormRules = ref<FormRules>({
  name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  legalPerson: [{ required: true, message: '请输入法人', trigger: 'blur' }],
  registeredAddress: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
  industryCode: [{ required: true, message: '请选择所在行业', trigger: 'change' }],
  contact: [{ required: true, message: '请输入企业联系人', trigger: 'blur' }],
  contactNumber: [{ required: true, message: '请输入联系人电话', trigger: 'blur' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  businessLicenseUrl: [{ required: true, message: '请上传营业执照', trigger: 'change' }]
})
const refForm = ref<FormInstance>()
const clearForm = () => {
  refForm.value?.resetFields()
}
const onSubmit = async () => {
 if(route.params.id){
  await updateParkAPI({...addForm.value,id:editId.value})
  ElMessage.success('修改成功')
  router.back()
 }else{
  try {
    submitLoding.value = true
    await refForm.value?.validate()
    await addParkAPI(addForm.value)
    ElMessage.success('添加成功')
    router.back()
  } catch (err) {
    console.log(err);
    submitLoding.value = false
  }
 }
}
const onRemove = () => {
  addForm.value.businessLicenseUrl = ''
  refForm.value?.validateField('businessLicenseUrl')
}
const submitLoding = ref(false)
onMounted(async()=>{
 if(route.params.id){
  const res=await editParkAPI(String(route.params.id))
  const {name,legalPerson,registeredAddress,industryCode,contact,contactNumber,businessLicenseUrl,businessLicenseId,id}=res.data
  addForm.value={name,legalPerson,registeredAddress,industryCode,contact,contactNumber,businessLicenseUrl,businessLicenseId}
  fileList.value=[{url:businessLicenseUrl,name:'执照'}]
  editId.value=id
 }
})
</script>


<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="$route.params.id?'修改企业':'添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="refForm" label-width="100px" :model="addForm" :rules="addFormRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option v-for="item in industryRes" :key="item.industryCode" :label="item.industryName"
                  :value="item.industryCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" maxlength="11" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <!-- accept=".jpg,.png" -->
              <el-upload :http-request="upload" :limit="1" list-type="picture" :before-upload="uploadRule"
                @remove="onRemove" v-model:file-list="fileList">
                <el-button type="primary" :icon="UploadFilled" v-if="fileList.length === 0">点击上传</el-button>
                <el-button type="success" :icon="SuccessFilled" v-else disabled>上传成功</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    "大小小于500KB的jpg/png文件"
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="clearForm" :disabled="Boolean($route.params.id)">重置{{ addForm }}</el-button>
        <el-button v-if="!submitLoding" type="primary" @click="onSubmit">确定{{ fileList }}</el-button>
        <el-button v-if="submitLoding" type="primary" disabled :icon="Loading">上传中</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>